<template>
  <div class="page white-stage">
    <div class="team-main">
      <group class="no-margin">
        <x-input title="团队名称" v-model="team.team_name" placeholder="请输入团队名称" novalidate :icon-type="iconType" :show-clear="false" @on-blur="onBlur" placeholder-align="right"></x-input>
        <cell @click.native ="selectManager" direction="rtl" title="营销主管" :value="selectManagerValue"  ></cell>
        <cell @click.native="selectMembers" direction="rtl" title="营销顾问" :value="selectMembersValue" ></cell>
      </group>
      <div class="btn-group center-btn-group">
        <span class="btn save-btn" :class="{'disabled': disabled}" @click="saveTeam">保存</span>
      </div>
    </div>
    <x-dialog v-model="this.$store.state.app.dialogShow">
      <div class="dialog-message">
        {{ this.$store.state.app.dialogMessage }}
      </div>
      <span class="vux-close" @click="hideDialog">知道了</span>
    </x-dialog>
  </div>
</template>

<script>
  // import Vue from 'vue'
  // import clientMenu from '../components/client-menu'
  // import {XInput, Group, Selector, Cell} from 'vux'
  import store from '../store'
  // import {XDialog} from 'vux'
  import XInput from 'vux/src/components/x-input'
  import Group from 'vux/src/components/group'
  import Selector from 'vux/src/components/selector'
  import Cell from 'vux/src/components/cell'
  // import XAddress from 'vux/src/components/x-address'
  // import ChinaAddressData from 'vux/src/datas/china_address.json'
  // import Datetime from 'vux/src/components/datetime'
  import XDialog from 'vux/src/components/x-dialog'

  import {showDialog, hideDialog} from '../lib/dialog'
  import { mapActions } from 'vuex'

  export default {

    data() {
      return {
        team:{
          parent_id: "0"
        },
        disables: [],
        disabled: false,
        iconType: '',
        team_managers: [],
        team_members: [],
        selected_team_managers:[],
        selected_team_members:[],
        selectManagerValue: '选择营销主管',
        selectMembersValue: '请选择营销顾问',

        // clientSourceValue: '',
        // industryValue: '',
        // teamGenderValue: '',

        marketingChargers: [
        {
          key : '0',
          value: '李丽萍'
        },
        {
          key: '1',
          value: '林宇'
        }
        ],

        counselor : [

        {
          key: '0',
          value:'林丽亲'
        },

        {
          key:'1',
          value:'李美英'}
        ],

        amounts : [

        {
          key: '0',
          value:'100'
        },

        {
          key:'1',
          value:'50'
        }
        ]
      }
    },
    components:{
      XInput,
      Group,
      Selector,
      Cell,
      XDialog
    },
    methods: {
      refresh (iscroll) {
        console.log('refresh')
      // Refresh current data
      },

      log () {
        console.log('ee');
      },

      load (iscroll) {
        console.log('load')
        // Load new data
      },

      test () {
        console.log('test')
      },

      hideDialog : hideDialog,

      onBlur () {

      },
      initTeamInfo () {
        this.getTeams({page_size: 300})
        .then((response) => {
          if (response.data.errcode === 0) {
            let teams = typeof response.data.results.teams !== 'undefined' ? response.data.results.teams : []
            teams.forEach((team) => {
              if (team.id !== this.teamId) {
                team.team_managers.forEach((teamItem) => {
                  this.disables.push(teamItem.ding_user_id)
                })
                team.team_members.forEach((teamItem) => {
                  this.disables.push(teamItem.ding_user_id)
                })
              }
            })
          } else {
            console.log('response: ', JSON.stringify(response.data));
          }
        }).catch((error) =>{
          console.debug(error, JSON.stringify(response.data))
        })
      },
      saveTeam() {

        let that = this
        if (this.disabled === true) {
          showDialog('请勿重复提交')
          return
        }
        this.disabled = true

        store.dispatch('saveTeams', that.team)
          .then(function(response){
            if(response.data.errcode === 0) {
              showDialog(response.data.errmsg)
              setTimeout(() => {
                that.$router.back()
              },2000)
            } else {
              console.debug('系统出错!请联系管理员', response.data);
              showDialog(response.data.errmsg)
            }
            this.disabled = false
          }).catch((error) => {
            this.disabled = false
            console.debug(error, '系统出错!请联系管理员')
          });
      },

      onShow () {
        this.callJsApi('biz.navigation.setTitle',{title:'新增团队'});
      },

      selectManager () {

        console.log('selectManager')
        var that = this;
        let users = [];

        this.selected_team_managers
        .forEach(function(element){
          users.push(element.emplId);
        })


        this.callJsApi('biz.contact.choose',{users: users})
        .then(function(data){
          console.log(JSON.stringify(data));

          var team_managers = [];

          data.forEach(function(object, index){
            team_managers.push({
              ding_user_id : object.emplId,
              name : object.name
            })
          });

          that.team_managers = team_managers;
          that.team.team_managers = team_managers;
          that.selected_team_managers = data;
        });
    },

    selectMembers () {
      console.log('selectMembers')
      var that = this;
      let users = [];

      this.selected_team_members.forEach(function(element){
        users.push(element.emplId);
      })

      this.callJsApi('biz.contact.choose', {
        users: users,
        disabledUsers: this.disables
      }).then(function(data){
          var team_members = []
          let existsMembers = []
          let selectedMembers = []

          data.forEach(function(object, index) {
            if (that.disables.indexOf(object.emplId) > -1) {
              existsMembers.push(object.name)
            } else {
              team_members.push({
                ding_user_id : object.emplId,
                name : object.name
              })
              selectedMembers.push(object)
            }
          });

          console.log(existsMembers, 'existsMembers')
          if (existsMembers.length) {
            showDialog('“' + existsMembers.join(',') + '” 已经成为其他团队的顾问，不能再加入当前团队')
          }

          console.log(that, 'team_members');

          that.team_members = team_members;
          that.team.team_members = team_members;
          that.selected_team_members = selectedMembers
        });
      },
      ...mapActions({
        'getTeams': 'getTeams'
      })
    },

    watch:{

      mkChargerValue(value){
        this.team.orderway = value;
      },
      counselorValue(value){
        this.team.counselor = value;
      },
      amountValue(value){
        this.team.amount = value;
      },

      team_members(value) {

        var selectManagerValue = '';
        var isNotElippse = false;

        this.selected_team_members.forEach(function(object, index){
          if(index < 3) {
            selectManagerValue += (index === 0 ? '' : '、')+object.name;
          } else if(isNotElippse === false) {
            selectManagerValue += '...';
            isNotElippse = true;
          }
        });

        this.selectMembersValue = selectManagerValue;
      },

      team_managers(value) {

        var selectManagerValue = '';
        var isNotElippse = false;

        this.selected_team_managers.forEach(function(object, index){
          if(index < 3) {
            selectManagerValue += (index === 0 ? '' : '、')+object.name;
          } else if(isNotElippse === false) {
            selectManagerValue += '...';
            isNotElippse = true;
          }
        });

        this.selectManagerValue = selectManagerValue;
      }

    },

    mounted() {
      this.initTeamInfo()
      this.callJsApi('biz.navigation.setTitle',{title:'新增团队'});
    },


  }
</script>

<style lang='less'>
  @import "../less/index.less";

  .team-main{

  .no-margin{
     &>*{
     margin: 0
     }
  }

  .add-new-btn{
    width: 60%;
  }

  .btn-group{
    margin-top: 15px;

    &>*{
    width: 80%;
    text-align: center;
    border-radius: 4px;
    padding: 10px;
    margin: 0 auto;
    border: 1px solid rgb(229, 229, 229);
    background-color: white;
    color:#23B2E2;
    display: block;
    }

    .pull-left{
    float: left;
    }

    .pull-right{
    float: right;
    }
  }

  .cell::before {
    content: " ";
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    height: 1px;
    border-top: 1px solid #D9D9D9;
    color: #D9D9D9;
    -webkit-transform-origin: 0 0;
        transform-origin: 0 0;
    -webkit-transform: scaleY(0.5);
        transform: scaleY(0.5);
    left: 15px;
    }

  }
</style>
